package com.lifeng.controller;

import com.lifeng.constant.ResCodeConstant;
import com.lifeng.domain.SysUser;
import com.lifeng.dto.LoginDto;
import com.lifeng.service.SysUserService;
import com.lifeng.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:lifeng
 * @date:2020/4/9 11:18
 */
@RestController
@Slf4j
public class LoginController {
    @Resource
    private TokenService tokenService;
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/login")
    public Object login(LoginDto loginDto){
        Map<String,Object> res = new HashMap<>();
        SysUser sysUser = sysUserService.findByUserNameAndPwd(loginDto.getUserName(),loginDto.getPassWord());
        if(sysUser!=null){
            String token = tokenService.creteToken(loginDto);
            res.put("token",token);
            res.put("userinfo",loginDto);
            res.put("code", ResCodeConstant.C0);
        }else{
            log.warn("用户名或密码不正确");
            res.put("code",ResCodeConstant.C1001);
            res.put("msg","用户名或密码不正确");
        }
        return res;
    }

    @RequestMapping("/logout")
    public Object logout(HttpServletRequest request){
        Map<String,Object> res = new HashMap<>();
        LoginDto user = tokenService.getLoginInfo(request);
        if(user!=null){
            String token = request.getHeader("token");
            tokenService.deleteToken(token);
        }
        res.put("code",0);
        res.put("msg","退出成功");
        return res;
    }
}
